﻿using System;
using System.Collections.Generic;
using NHibernate;
using Common;
using Educational.Model.Entity;
using Educational.Model.EntityManager;

namespace Educational.Business
{
    public class SchoolAdmin
    {
        #region CreateSchoolBySystem一键自动生成学校需要的相关数据
        public static void CreateSchoolBySystem(int schoolId)
        {
            ISession session = null;
            ITransaction trans = null;
            try
            {
                session = NHibernateHelper.OpenSession();
                trans = session.BeginTransaction();
                School school = SchoolManager.Get(session, schoolId);
                if (school == null)
                    throw new Exception("当前学校不存在或者已经被删除");
                if (school.loginTimes !=1)
                    throw new Exception("只允许在第一次登录时自动生成相关数据！");
                trans.Commit();
            }
            catch
            {
                if (trans != null)
                    trans.Rollback();
                throw;
            }
            finally
            {
                if (session != null)
                    session.Close();
            }
            DepartmentAdmin.AddDepartment(schoolId, 0, "校委会");
            DepartmentAdmin.AddDepartment(schoolId, 0, "班主任组");
            DepartmentAdmin.AddDepartment(schoolId, 0, "语文组");
            DepartmentAdmin.AddDepartment(schoolId, 0, "数学组");
            DepartmentAdmin.AddDepartment(schoolId, 0, "外语组");
            DepartmentAdmin.AddDepartment(schoolId, 0, "理化生组");
            DepartmentAdmin.AddDepartment(schoolId, 0, "政史地组");
            DepartmentAdmin.AddDepartment(schoolId, 0, "综合组");
            DepartmentAdmin.AddDepartment(schoolId, 0, "后勤组");
        }
        #endregion

        #region 添加一个学校注册申请
        /// <summary>
        /// 添加一个学校注册申请
        /// </summary>
        /// <param name="typeId"></param>
        /// <param name="schoolName"></param>
        /// <param name="legalRepresentative"></param>
        /// <param name="telnumber"></param>
        /// <param name="loginId"></param>
        /// <param name="loginPass"></param>
        public static void AddSchool(
            int typeId, 
            string schoolName, 
            string legalRepresentative, 
            string telnumber, 
            string loginId, 
            string loginPass
        )
        {
            if (String.IsNullOrEmpty(schoolName) || String.IsNullOrEmpty(loginId) || String.IsNullOrEmpty(loginPass))
                throw new Exception("学校名称,登录ID，登录密码不能为空");
            ISession session = null;
            ITransaction trans = null;
            School school = null;
            try
            {
                session = NHibernateHelper.OpenSession();
                trans = session.BeginTransaction();

                if (SchoolManager.Get1(session, loginId) != null)
                    throw new Exception("当前系统已存在这个登录ID，请换一个登录ID。");
                school = new School();
                school.lastLoginIp = "";
                school.lastLoginTime = DateTime.Now;
                school.legalRepresentative = legalRepresentative;
                school.loginId = loginId;
                school.loginPass = loginPass;
                school.loginTimes = 0;
                school.schoolName = schoolName;
                school.regTime = DateTime.Now;
                school.status = 0;
                school.telnumber = telnumber;
                Basic.Model.Entity.Dictionary schoolType = Basic.Model.EntityManager.DictionaryManager.Get(session, typeId);
                if (schoolType == null)
                    throw new Exception("当前字典不存在这个值");
                school.schoolType = schoolType;
                SchoolManager.Add(session, school);

                trans.Commit();
            }
            catch
            {
                if (trans != null)
                    trans.Rollback();
                throw;
            }
            finally
            {
                if (session != null)
                    session.Close();
            }
        }
        #endregion

        #region 更改学校状态
        /// <summary>
        /// 更改学校状态
        /// </summary>
        /// <param name="schoolId"></param>
        /// <param name="status"></param>
        public static void UpdateSchoolStatus(int schoolId, int status)
        {
            ISession session = null;
            ITransaction trans = null;
            School school = null;
            try
            {
                session = NHibernateHelper.OpenSession();
                trans = session.BeginTransaction();
                school = SchoolManager.Get(session, schoolId);
                if (school == null)
                    throw new Exception("不存在这个数据或者这个数据已经被删除");
                school.status = status;
                trans.Commit();
            }
            catch
            {
                if (trans != null)
                    trans.Rollback();
                throw;
            }
            finally
            {
                if (session != null)
                    session.Close();
            }
        }
        #endregion

        #region ChangePassword修改登录密码
        /// <summary>
        /// 修改登录密码
        /// </summary>
        /// <param name="SchoolId"></param>
        /// <param name="oldMd5Password"></param>
        /// <param name="newMd5Password"></param>
        public static void ChangePassword(int schoolId, string oldMd5Password, string newMd5Password)
        {
            ISession session = null;
            ITransaction trans = null;
            School school = null;
            try
            {
                session = NHibernateHelper.OpenSession();
                trans = session.BeginTransaction();
                school = SchoolManager.Get(session, schoolId);
                if (school == null)
                    throw new Exception("不存在这个数据或者这个数据已经被删除");
                if (!school.loginPass.Equals(oldMd5Password))
                    throw new Exception("原密码错误");
                school.loginPass = newMd5Password;
                trans.Commit();
            }
            catch
            {
                if (trans != null)
                    trans.Rollback();
                throw;
            }
            finally
            {
                if (session != null)
                    session.Close();
            }
        }
        #endregion

        #region UpdateSchool修改学校信息
        /// <summary>
        /// 修改学校信息
        /// </summary>
        /// <param name="schoolId"></param>
        /// <param name="schoolName"></param>
        /// <param name="legalRepresentative"></param>
        /// <param name="telnumber"></param>
        public static void UpdateSchool(int schoolId, string schoolName, string legalRepresentative, string telnumber)
        {
            ISession session = null;
            ITransaction trans = null;
            School school = null;
            try
            {
                session = NHibernateHelper.OpenSession();
                trans = session.BeginTransaction();
                school = SchoolManager.Get(session, schoolId);
                if (school == null)
                    throw new Exception("不存在这个数据或者这个数据已经被删除");
                if (String.IsNullOrEmpty(schoolName) || String.IsNullOrEmpty(legalRepresentative) || string.IsNullOrEmpty(telnumber))
                    throw new Exception("学校名称，负责人，联系电话均不能为空");
                school.schoolName = schoolName;
                school.legalRepresentative = legalRepresentative;
                school.telnumber = telnumber;
                trans.Commit();
            }
            catch
            {
                if (trans != null)
                    trans.Rollback();
                throw;
            }
            finally
            {
                if (session != null)
                    session.Close();
            }
        }
        #endregion

        #region 验证登录
        /// <summary>
        /// 验证登录
        /// </summary>
        /// <param name="loginId"></param>
        /// <param name="md5LoginPass"></param>
        /// <returns></returns>
        public static Educational.VO.School CheckLogin(string loginId, string md5LoginPass)
        {
            ISession session = null;
            ITransaction trans = null;
            Educational.VO.School school = null;
            School entityData = null;
            try
            {
                session = NHibernateHelper.OpenSession();
                trans = session.BeginTransaction();
                entityData = SchoolManager.Get2(session, loginId, md5LoginPass);
                if (SchoolManager.Get1(session,loginId)==null)
                    throw new Exception("该登录ID不存在");
                if (entityData == null)
                    throw new Exception("登录密码错误");
                if (entityData.status == 1)
                    throw new Exception("该学校已经被删除");
                if (entityData.status == 2)
                    throw new Exception("该学校已经被锁定");
                entityData.loginTimes += 1;
                school = new Educational.VO.School();
                school.lastLoginIp = entityData.lastLoginIp;
                school.lastLoginTime = Tools.ToDateTimeString(entityData.lastLoginTime);
                school.legalRepresentative = entityData.legalRepresentative;
                school.loginId = entityData.loginId;
                school.loginTimes = entityData.loginTimes;
                school.regTime = Tools.ToDateTimeString(entityData.regTime);
                school.schoolId = entityData.schoolId;
                school.schoolName = entityData.schoolName;
                school.status = entityData.status;
                school.telnumber = entityData.telnumber;
                school.schoolType = new Basic.VO.Dictionary();
                school.schoolType.dictionaryValue = entityData.schoolType.dictionaryValue;
                entityData.lastLoginTime = DateTime.Now;
                entityData.lastLoginIp = Tools.GetIpAddress();
                trans.Commit();
            }
            catch
            {
                if (trans != null)
                    trans.Rollback();
                throw;
            }
            finally
            {
                if (session != null)
                    session.Close();
            }
            return school;
        }
        #endregion

        #region 查询所有学校根据分页
        /// <summary>
        /// 查询所有未删除学校根据分页
        /// </summary>
        /// <param name="schoolName">学校名称，非必填</param>
        /// <param name="loginId">登录ID，非必填</param>
        /// <param name="rowIndex"></param>
        /// <param name="rowCount"></param>
        /// <returns></returns>
        public static PageResult<Educational.VO.School> GetsSchool(string schoolName, string loginId, int rowIndex, int rowCount)
        {
            IList<School> entityData = null;
            PageResult<Educational.VO.School> pageResult = new PageResult<Educational.VO.School>();
            pageResult.data = new List<Educational.VO.School>();
            ISession session = null;
            ITransaction trans = null;
            try
            {
                session = NHibernateHelper.OpenSession();
                trans = session.BeginTransaction();
                entityData = SchoolManager.Gets1(session, schoolName, loginId, rowIndex, rowCount);
                pageResult.totalCount = SchoolManager.Gets1Count(session, schoolName, loginId);
                trans.Commit();
            }
            catch
            {
                if (trans != null)
                    trans.Rollback();
                throw;
            }
            finally
            {
                if (session != null)
                    session.Close();
            }
            for (int i = 0; i < entityData.Count; i++)
            {
                Educational.VO.School school = new Educational.VO.School();
                school.lastLoginIp = entityData[i].lastLoginIp;
                school.lastLoginTime = Tools.ToDateTimeString(entityData[i].lastLoginTime);
                school.legalRepresentative = entityData[i].legalRepresentative;
                school.loginId = entityData[i].loginId;
                school.loginTimes = entityData[i].loginTimes;
                school.regTime = Tools.ToDateTimeString(entityData[i].regTime);
                school.schoolId = entityData[i].schoolId;
                school.schoolName = entityData[i].schoolName;
                school.status = entityData[i].status;
                school.telnumber = entityData[i].telnumber;
                school.schoolType = new Basic.VO.Dictionary();
                school.schoolType.dictionaryValue = entityData[i].schoolType.dictionaryValue;
                pageResult.data.Add(school);
            }
            return pageResult;
        }
        #endregion

        #region IsSchoolSessionValid验证该学校是否超时
        /// <summary>
        /// 验证该学校是否超时
        /// </summary>
        /// <returns></returns>
        public static bool IsSchoolSessionValid()
        {
            bool flag = false;
            System.Web.HttpContext.Current.Application.Lock();
            if (System.Web.HttpContext.Current.Session["school"] == null)
                flag = true;
            System.Web.HttpContext.Current.Application.UnLock();
            return !flag;
        }
        #endregion
    }
}
